package mainInterface

import java.awt.event.{ActionEvent, ActionListener, MouseEvent, MouseListener}
import java.awt.{Desktop, MenuItem, PopupMenu, SystemTray, TrayIcon}
import java.io.File
import java.net._
import java.util.{ResourceBundle, Timer, TimerTask}

import javafx.animation.{KeyFrame, PauseTransition, Timeline}
import javafx.application.{Application, Platform}
import javafx.event.EventHandler
import javafx.fxml.{FXML, Initializable}
import javafx.scene.control.{Button, Label}
import javafx.scene.image.Image
import javafx.scene.layout.{AnchorPane, Background, BackgroundImage, BackgroundPosition, BackgroundRepeat, BackgroundSize}
import javafx.scene.paint.Color
import javafx.stage.{Stage, WindowEvent}
import javafx.util.Duration
import javax.imageio.ImageIO
import org.apache.commons.io.FileUtils
import tool.Tool
import utils.Utils

import scala.collection.mutable.ArrayBuffer
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global


class MainInterfaceEvent extends Initializable {

  @FXML
  var execButton: Button = _
  @FXML
  var homeButton: Button = _
  @FXML
  var status: Label = _
  @FXML
  var anchorPane: AnchorPane = _
  var firstTime: Boolean = true

  override def initialize(location: URL, resources: ResourceBundle): Unit = {

    status.setTextFill(Color.web("#31708f"))
    setHomeDisable

    val myBI = new BackgroundImage(new Image(this.getClass.getResourceAsStream("back.png"), 600,
      400, false, true),
      BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT)
    anchorPane.setBackground(new Background(myBI))

  }

  def isAvail = {
    try {
      val address = InetAddress.getByName("127.0.0.1")
      var socket = new Socket(address, Tool.port)
      true
    } catch {
      case e => false
    }
  }

  @FXML
  def exec = {
    val stage = execButton.getScene.getWindow.asInstanceOf[Stage]
    if (execButton.getText == "启动") {
      Tool.runServer
      val alert = Utils.showInformation("信息", "服务正在启动，请稍候。。。", stage)
      val file = new File(Tool.workSpace, "RUNNING_PID")
      val pause = new PauseTransition(Duration.seconds(1))
      pause.setOnFinished((e) => {
        if (!isAvail) {
          pause.playFromStart()
        } else {
          alert.close()
          stage.toBack()
          status.setText("服务正在运行...")
          status.setTextFill(Color.web("#3c763d"))
          execButton.setText("关闭")
          setHomeDisable
          toHome
        }
      })
      pause.play()
    } else {
      Tool.stopServer
      status.setText("服务未启动！")
      status.setTextFill(Color.web("#31708f"))
      execButton.setText("启动")
      setHomeDisable
    }

  }

  @FXML
  def toHome = {
    val uri = new URI(s"http://localhost:${Tool.port}")
    Desktop.getDesktop.browse(uri)

  }

  @FXML
  def mini = {
    val stage = execButton.getScene.getWindow.asInstanceOf[Stage]
    enableTray(stage)
  }

  def setHomeDisable = {
    if (isAvail) {
      homeButton.setDisable(false)
    } else {
      homeButton.setDisable(true)
    }

  }

  def enableTray(stage: Stage) = {
    if (SystemTray.isSupported) {
      if (firstTime) {
        createTrayIcon(stage)
      } else {
        hide(stage)
      }
    }


  }


  def createTrayIcon(stage: Stage) = {
    val popuMenu = new PopupMenu()
    val openItem = new MenuItem("显示")
    val exitItem = new MenuItem("退出")
    val acl = new ActionListener() {
      override def actionPerformed(e: ActionEvent): Unit = {
        val item = e.getSource.asInstanceOf[MenuItem]
        Platform.setImplicitExit(false)
        if (item.getLabel.equals("显示")) {
          show(stage)
        }
        if (item.getLabel.equals("退出")) {
          Tool.exit
        }

      }
    }
    openItem.addActionListener(acl)
    exitItem.addActionListener(acl)

    popuMenu.add(openItem)
    popuMenu.add(exitItem)

    val tray = SystemTray.getSystemTray
    val is = this.getClass.getClassLoader.getResourceAsStream("tray.png")
    val image = ImageIO.read(is)
    val trayIcon = new TrayIcon(image, "脂肪肝数据分析软件", popuMenu)
    tray.add(trayIcon)

    val sj = new MouseListener() {
      override def mouseClicked(e: MouseEvent): Unit = {
        Platform.setImplicitExit(false)
        if (stage.isShowing) {
          Platform.runLater(() => {
            stage.setIconified(false)
            stage.requestFocus()
          })
        } else {
          show(stage)
        }

      }

      override def mousePressed(e: MouseEvent): Unit = {

      }

      override def mouseReleased(e: MouseEvent): Unit = {

      }

      override def mouseEntered(e: MouseEvent): Unit = {

      }

      override def mouseExited(e: MouseEvent): Unit = {

      }
    }

    trayIcon.addMouseListener(sj)
    Platform.setImplicitExit(false)
    Platform.runLater(() => {
      stage.hide()
      firstTime = false
    })

  }

  def hide(stage: Stage) = {
    Platform.runLater(() => {
      stage.hide()
    })

  }

  def show(stage: Stage) = {
    Platform.runLater(() => {
      stage.show()
    })

  }


}
